package com.wangjialu.learner.payment.controller;

import com.wangjialu.learner.payment.entities.Payment;
import com.wangjialu.learner.payment.service.PaymentService;
import com.wangjialu.learner.payment.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p></p>
 *
 * @author WangJialu
 * @since 2021/6/22 4:44
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private Integer port;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/insert")
    public CommonResult insert(@RequestBody Payment payment) {
        int result = paymentService.insert(payment);
        log.debug("********插入结果：" + result);
        if (result > 0) {
            return new CommonResult(200, "success:port:" + port, result);
        }
        return new CommonResult(444, "插入数据失败:port:" + port);
    }

    @GetMapping("/payment/getById/{id}")
    public CommonResult<Payment> getById(@PathVariable("id") Long id) {
        Payment payment = paymentService.queryById(id);
        log.debug("********查询结果：" + payment);
        if (null != payment) {
            return new CommonResult(200, "success:port:" + port, payment);
        }
        return new CommonResult(444, "没有对应记录:port:" + port);
    }

    @GetMapping("/payment/discovery")
    public CommonResult<DiscoveryClient> discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.debug("*********element:"+service);
        }
        // 一个微服务下的全部实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.debug(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + instance.getUri());
        }
        return new CommonResult(200, "success:port:" + port, discoveryClient);
    }

    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        return String.valueOf(port);
    }
}
